package com.tanklab.signature.controller;

import com.tanklab.signature.common.util.JwtUtils;
import com.tanklab.signature.common.util.ResultCode;
import com.tanklab.signature.ds.resp.CommonResp;
import com.tanklab.signature.service.RequestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/signature/request")
@Api(tags = "申请管理")
public class RequestController {

    @Autowired
    private RequestService requestService;

    @Autowired
    private JwtUtils jwtUtils;

    @ApiOperation(value = "查询所有请求")
    @GetMapping("/list")
    public CommonResp getAllRequests(
            @ApiParam(value = "状态过滤", allowableValues = "pending,approve,reject")
            @RequestParam(required = false) String status,
            HttpServletRequest request) {

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            CommonResp resp = new CommonResp();
            resp.setRet(ResultCode.TOKEN_MISS);
            resp.setMsg("未提供有效token");
            return resp;
        }

        token = token.substring(7);
        // 从token中获取openid
        String openid = jwtUtils.getOpenidFromToken(token);

        // 调用服务查询所有Request
        return requestService.queryAllRequests(openid, status);
    }

    @ApiOperation(value = "查询待审批请求")
    @GetMapping("/pending")
    public CommonResp getPendingRequests(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            CommonResp resp = new CommonResp();
            resp.setRet(ResultCode.TOKEN_MISS);
            resp.setMsg("未提供有效token");
            return resp;
        }

        token = token.substring(7);
        String openid = jwtUtils.getOpenidFromToken(token);

        return requestService.queryPendingRequests(openid);
    }
}